<template>
  <div class="group-page">
    <div class="header">
      <search />
      <category :group="group" @clickCategory="clickCategory" />
    </div>
    <div class="no"></div>
    <swiper :group="group" v-if="haveSwiper" />
    <product :class="{'no-swiper': !haveSwiper}" :category="category" :quantity="group.quantity" />
    <loading :show="loading" />
  </div>
</template>

<script>
import Search from '@/components/Search'
import Category from './components/Category'
import Swiper from './components/Swiper'
import Product from './components/Product'

import api from '@/api'
import base64 from '@/util/base64'
import Loading from '@/components/Loading'
export default {
  name: 'Group',
  components: {
    Category,
    Product,
    Search,
    Swiper,
    Loading
  },
  computed: {
    haveSwiper() {
      return this.group.swiper && this.group.swiper.length > 0
    }
  },
  data() {
    return {
      group: {
        quantity: -1
      },
      loading: false,
      category: 0
    }
  },
  methods: {
    /**
     * get uni group data (swiper & category)
     * 1) vuex
     * 2) localstorage
     * 3) redis
     * 4) db
     */
    fetchData() {
      const data = this.$store.getters['Group/group']
      if (data === null) {
        this.loading = true
        api.Uni.groupPage().then(response => {
          let { data } = response
          data = base64.parse(data)
          this.$store.dispatch('Group/set_data', data).then(() => {
            this.group = data
          })
        }).finally(() => {
          this.loading = false
        })
      } else {
        this.group = data
      }
    },
    clickCategory(id) {
      this.category = id
    }
  },
  created () {
    this.fetchData()
  }
}
</script>

<style scoped lang="stylus">
.group-page
  background $background_color
  .header
    position fixed
    z-index 10
    top 0
    left 0
    width 100%
  .no-swiper
    margin-top 110px
  .no
    height 10px
</style>
